package com.genwangsun.nettydemo.websocket;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.handler.timeout.WriteTimeoutHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author GenWangSun
 */
@Component
@Slf4j
public class NettyServerInitializer extends ChannelInitializer<SocketChannel> {
    @Autowired
    private WebSocketServerHandler webSocketServerHandler;

    private static final int READ_IDLE_TIME_OUT = 120; // 读超时
    private static final int WRITE_IDLE_TIME_OUT = 120;// 写超时
    private static final int ALL_IDLE_TIME_OUT = 120; // 所有超时

    @Override
    protected void initChannel(SocketChannel socketChannel) {
        ChannelPipeline pipeline = socketChannel.pipeline();
        pipeline.addLast(new ReadTimeoutHandler(24 * 60, TimeUnit.MINUTES));
        pipeline.addLast(new IdleStateHandler(READ_IDLE_TIME_OUT, WRITE_IDLE_TIME_OUT, ALL_IDLE_TIME_OUT, TimeUnit.MINUTES));
        //http解码器
        pipeline.addLast(new HttpServerCodec());
        //支持写大数据流
        pipeline.addLast(new ChunkedWriteHandler());
        //http聚合器
        pipeline.addLast(new HttpObjectAggregator(1024 * 62));
        pipeline.addLast(new WebSocketServerProtocolHandler("/biz"));
        pipeline.addLast(webSocketServerHandler);
    }
}
